package com.zero.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.netflix.discovery.converters.Auto;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.zero.dao.OrderDao;
import com.zero.entity.Order;
import com.zero.entity.Result;
import com.zero.feign.StorageFeign;
import com.zero.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * (Order)表服务实现类
 *
 * @author makejava
 * @since 2022-04-24 18:02:20
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order>  implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private StorageFeign storageFeign;

    /**
     * 创建订单，并返回订单号
     * @param goodsId 商品id
     * @param count 购买数量
     * @return 订单创建结果
     */
    @Override
    @Transactional
    @HystrixCommand(
        groupKey = "order-service",
        commandKey = "createOrder",
        threadPoolKey = "order-service-threadPool",
        threadPoolProperties = {
            @HystrixProperty(name = HystrixPropertiesManager.CORE_SIZE, value = "8"),
            @HystrixProperty(name = HystrixPropertiesManager.MAX_QUEUE_SIZE, value = "10"),
            @HystrixProperty(name = HystrixPropertiesManager.QUEUE_SIZE_REJECTION_THRESHOLD, value = "5"),
            @HystrixProperty(name = HystrixPropertiesManager.KEEP_ALIVE_TIME_MINUTES, value = "2")
        },
        fallbackMethod = "myFallback"
    )
    public String createOrder(int goodsId, int count) {
        // 先扣除库存，如果库存扣除成功才创建订单
        Result result = storageFeign.deductStorage(goodsId, count);
        if (result.getCode() != 1) {
            return String.format("订单创建失败！原因：%s", result.getMessage());
        }
        // 创建订单，假设需要秒杀的商品价格是50元
        String orderId = UUID.randomUUID().toString().replace("-", "");
        Integer createResult = orderDao.createOrder(new Order(orderId, goodsId, count, 50.0 * count));
        if (createResult == 1) {
            return String.format("订单创建成功！订单号：%s, thread=%s", orderId, Thread.currentThread().getName());
        }
        return String.format("订单创建失败！原因：订单失效");
    }

    public String myFallback(int goodsId, int count) {
        return "正在为您排队，请稍候。。。";
    }
}

